//
//  BoxTableViewController.m
//  myhuibao
//
//  Created by li jun on 13-3-8.
//  Copyright (c) 2013年 myhuibao. All rights reserved.
//

#import "BoxTableViewController.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "SBJson.h"
#import "BoxCell.h"
#import "OMGToast.h"
#import "BoxPhotoViewController.h"

@interface BoxTableViewController ()

@end

@implementation BoxTableViewController
@synthesize mainTable;
@synthesize delegatePassValue;
@synthesize selectedIds;
@synthesize req;
@synthesize reqBoxType;
@synthesize reqCapacity;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
- (void)startRequest
{
    if(!loadingView)
    {
        loadingView = [[RequestLoadingView alloc]
                       initRequestLoadingView:self
                       queueFinishSelector:nil
                       viewFrame:LoadingViewFrame];
    }
    
    [self getSearchResult];
    [self getBoxType];
    [self getCapacity];
    
    [loadingView addRequestToQueue:req];
    [loadingView addRequestToQueue:reqBoxType];
    [loadingView addRequestToQueue:reqCapacity];
    
    [loadingView startRequestQueue];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    wqTable = mainTable;


    
    [self startRequest];
}


- (void)viewDidUnload
{
    [self setMainTable:nil];
    [self setLbBoxType:nil];
    [self setLbCapacity:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void) getSearchResult{
    //异步请求
        
    NSURL *url = [NSURL URLWithString:url_boxList];
    req=[ASIFormDataRequest requestWithURL:url];
    [req setPostValue:[NSString stringWithFormat:@"%d",_merchantId] forKey:@"merchantID"];
    [req setPostValue:[NSString stringWithFormat:@"%@",_diningDate] forKey:@"diningDate"];
//    [req setPostValue:[NSString stringWithFormat:@"%d",_diningTime] forKey:@"diningTime"];
    [req setPostValue:[NSString stringWithFormat:@"%d",_diningHour] forKey:@"diningHour"];
    [req setPostValue:[NSString stringWithFormat:@"%d",_diningMin] forKey:@"diningMin"];

    if(boxType !=0)
        [req setPostValue:[NSString stringWithFormat:@"%d",boxType] forKey:@"boxType"];
    if(capacityId !=0)
        [req setPostValue:[NSString stringWithFormat:@"%d",capacityId] forKey:@"capacityId"];
    [req setShouldAttemptPersistentConnection:NO];
    [req setDidFinishSelector:@selector(finishReq:)];
    isReqFinished = false;
    [req setDelegate: self];
        
    if (!loadingView.bFirstRequest)
    {
        [req startAsynchronous];
    }

}
//下面是两个代理函数,当数据请求成功时会调用requestFinished，请求失败时（如网络问题或服务器内部错误）会调用requestFailed
- (void)finishReq:(ASIHTTPRequest *)request
{
    // Use when fetching text data
    isReqFinished = true;
    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [jsonStr JSONValue];
    
    tableDataArray = [dic valueForKey:@"data"];
    NSArray *ss = [selectedIds componentsSeparatedByString:@","];
    //NSLog(@"%@",tableDataArray);
    int returnCount = tableDataArray.count;
    if (returnCount==0) {
        [OMGToast showWithText:@"暂无空闲包厢。" bottomOffset:100];
    }
    for(int i=0;i<tableDataArray.count;i++)
    {
        NSMutableDictionary *item = [tableDataArray objectAtIndex:i];
        bool selected = [self isArray:ss contain:[NSString stringWithFormat:@"%d",[[item valueForKey:@"BOX_ID"] intValue] ]];
        if (selected)
            [item setValue:@"YES" forKey:@"checked"];
        else
            [item setValue:@"NO" forKey:@"checked"];
    }
    //保存全部包厢数据
    allArray = [tableDataArray copy];
    delegate=self;

    [mainTable reloadData];
    // Use when fetching binary data
    //    NSData *responseData = [request responseData];
}
- (void) getBoxType{
    //异步请求
    NSURL *url = [NSURL URLWithString:url_boxType];
    reqBoxType = [ASIHTTPRequest requestWithURL:url];
    [reqBoxType setDidFinishSelector:@selector(finishBoxType:)];
    isBoxTypeFinished = false;
    [reqBoxType setShouldAttemptPersistentConnection:NO];
    [reqBoxType setDelegate: self];
    

    if (!loadingView.bFirstRequest) {
        [reqBoxType startAsynchronous];
    }

    
}
- (void) getCapacity{
    //异步请求
    NSURL *url = [NSURL URLWithString:url_boxCapacity];
    reqCapacity = [ASIHTTPRequest requestWithURL:url];
    [reqCapacity setDidFinishSelector:@selector(finishCapacity:)];
    isCapacityFinished = false;
    [reqCapacity setShouldAttemptPersistentConnection:NO];
    [reqCapacity setDelegate: self];
    
    if(!loadingView.bFirstRequest)
    {
        [reqCapacity startAsynchronous];
    }

}
- (void)finishCapacity:(ASIHTTPRequest *)request
{
    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [jsonStr JSONValue];
    arrayCapacity = [dic valueForKey:@"data"];
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                          @"0",@"boxCapacityID",@"不限",@"boxCaptcityDesc",nil];
    [arrayCapacity insertObject: dict atIndex:0];
    isCapacityFinished = true;
}
- (void)finishBoxType:(ASIHTTPRequest *)request
{
    // Use when fetching text data
    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [jsonStr JSONValue];
    arrayBoxType = [dic valueForKey:@"data"];
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                          @"0",@"boxTypeID",@"不限",@"boxTypeDesc",nil];
    [arrayBoxType insertObject: dict atIndex:0];
    isBoxTypeFinished = true;
}
- (bool)isArray:(NSArray *)a contain:(NSString*)s
{    
    for(NSString *ss in a)
    {
        if ([s isEqualToString:ss]) {
            return true;
        }
    }
    return false;
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
    NSError *error = [request error];
    NSLog(@"%@",error);
    isReqFinished = true;
    isBoxTypeFinished = true;
    isCapacityFinished = true;
}


// 列表设置
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	int count = [tableDataArray count];
    return count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 84;
}
- (CGFloat)tableView:(UITableView *)tableView widthForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 320;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	static NSString *CellIdentifier = @"BoxCellIdentifier";
    
    BoxCell *cell = (BoxCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            if (cell == nil) {
    NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"BoxCell" owner:nil options:nil];
    cell = [array objectAtIndex:0];
    [cell setSelectionStyle:UITableViewCellSelectionStyleGray];
            }
    
    NSDictionary *item = [tableDataArray objectAtIndex:indexPath.row];
    NSString *lowestConsume =@"无最低消费";
    if([item valueForKey:@"LOWEST_CONSUME"] != [NSNull null]
            && [[item valueForKey:@"LOWEST_CONSUME"] intValue]!=0)
        lowestConsume = [NSString stringWithFormat:@"最低消费%@",[item valueForKey:@"LOWEST_CONSUME"]];
    cell.lbName.text = [item valueForKey:@"BOX_NAME"];
    cell.lbMemo.text =[NSString stringWithFormat:@"%@,%@,%@",
                        [item valueForKey:@"SEAT_TYPE"],
                        [item valueForKey:@"BOX_TYPE"],
                        lowestConsume];
    NSString * other = @"";
    if([item valueForKey:@"REST_AREA"] != [NSNull null]&& [[item valueForKey:@"REST_AREA"] intValue]==1)
        other = [NSString stringWithFormat:@"%@%@、",other,@"休息区"];
    if([item valueForKey:@"PLAY_TABLE"] != [NSNull null]&& [[item valueForKey:@"PLAY_TABLE"] intValue]==1)
        other = [NSString stringWithFormat:@"%@%@、",other,@"牌桌"];
    if([item valueForKey:@"HAS_TOILET"] != [NSNull null]&& [[item valueForKey:@"HAS_TOILET"] intValue]==1)
        other = [NSString stringWithFormat:@"%@%@、",other,@"卫生间"];
    if(![other isEqualToString:@""]){
        other = [other substringToIndex:other.length-1];
        cell.lbOther.text = [NSString stringWithFormat:@"%@:%@",@"其他设施",other];
    }else
        cell.lbOther.hidden = true;
    cell.checked = [[item valueForKey:@"checked"] boolValue];
    //        显示图片
    NSString * imageStr = [item valueForKey:@"IMAGE_PATH"];
    //向boxcell的imagepath传值，用于显示包厢图册
    cell.imagepath = imageStr;
    NSString *imageName =@"";
    if (![imageStr isEqual:[NSNull null] ]) {
        NSArray *aArray = [imageStr componentsSeparatedByString:@","];
        
        NSString * defaultImage = [[aArray objectAtIndex:0] stringByReplacingOccurrencesOfString:@"[imageSize]" withString:@"small"];
//        NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
//                              @"image",defaultImage,nil];
        [item setValue:defaultImage forKey:@"image"];
        
        NSArray *array = [defaultImage componentsSeparatedByString:@"/"];
        imageName = [array lastObject];
//        imageName = [imageName stringByReplacingOccurrencesOfString:@"[imageSize]" withString:@"small"];
    }
    NSString *imageDataPath = [NSHomeDirectory() stringByAppendingPathComponent:[@"Library/Caches/" stringByAppendingString:imageName==nil?@"":imageName]];
    UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfFile:imageDataPath]];
    if (image) {
        cell.imageView.image = image;
    }
    else
    {
        cell.imageView.image = [UIImage imageNamed:@"placeholder.png"];
        //placeholder为在未加载完成加载图片时显示的默认图片
    }
    //NSLog(@"%@",item);

    return cell;
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *item = [tableDataArray objectAtIndex:indexPath.row];
    BOOL checked = [[item valueForKey:@"checked"] boolValue];
    BoxCell *cell = (BoxCell*)[tableView cellForRowAtIndexPath:indexPath];
    if (checked) {
        [cell setChecked:false];
        [item setValue:@"NO" forKey:@"checked"];

    }else{
        [cell setChecked:true];
        [item setValue:@"YES" forKey:@"checked"];

    }
	
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
    //其他cell的事件
    
}
-(void)cellImageDidLoad:(NSIndexPath *)indexPath image:(UIImage *)image
{
    dispatch_async(dispatch_get_main_queue(), ^{
        UITableViewCell *cell = [wqTable cellForRowAtIndexPath:indexPath];
        if(image)
        {
            cell.imageView.image = image;
        }
    });
}
- (IBAction)doBack:(id)sender {
    if (!isReqFinished){
        [req clearDelegatesAndCancel];
        [req cancel];
    }if (!isCapacityFinished){
        [reqCapacity clearDelegatesAndCancel];
        [req cancel];
    }if (!isBoxTypeFinished){
        [reqBoxType clearDelegatesAndCancel];
        [reqBoxType cancel];
    }
    [self.navigationController popViewControllerAnimated:YES];
//    [self dismissModalViewControllerAnimated:YES];
}

- (IBAction)doSave:(id)sender {
    NSString *ids=@"";
    NSString *names=@"";
    for(int i=0;i<tableDataArray.count;i++)
    {
        NSMutableDictionary *item = [tableDataArray objectAtIndex:i];
        BOOL checked = [[item valueForKey:@"checked"] boolValue];
        if(checked)
        {
            ids = [ids stringByAppendingFormat:@"%@,",[item valueForKey:@"BOX_ID"]];
            names = [names stringByAppendingFormat:@"%@,",[item valueForKey:@"BOX_NAME"]];
        }
    }
//    if([ids isEqualToString:@""]==NO){
//        NSLog(@"%@", names);
        [delegatePassValue passBoxNames:names withIds:ids];
        [self.navigationController popViewControllerAnimated:YES];

//    }else{
//        [OMGToast showWithText:@"请选择包厢后点击完成。" bottomOffset:100];
//        [self.navigationController popViewControllerAnimated:YES];

//    }
}

- (IBAction)showBoxType:(id)sender {
    selectIndex = 5;
    LeveyPopListView *lplv = [[LeveyPopListView alloc] initWithTitle:@"请选择包厢类型" options:arrayBoxType];
    lplv.name = @"boxTypeDesc";
    lplv.selectedIndex = _selectedIndex3;
    lplv.delegate = self;
    [lplv showInView:self.view animated:YES];
}

- (IBAction)showCapacity:(id)sender {
    selectIndex = 6;
    LeveyPopListView *lplv = [[LeveyPopListView alloc] initWithTitle:@"请选择包厢大小" options:arrayCapacity];
    lplv.name = @"boxCaptcityDesc";
    lplv.selectedIndex = _selectedIndex2;
    lplv.delegate = self;
    [lplv showInView:self.view animated:YES];
}
#pragma mark - LeveyPopListView delegates
- (void)leveyPopListView:(LeveyPopListView *)popListView didSelectedIndex:(NSInteger)anIndex options:(NSArray *)_options didSelectedTypeIndex:(NSInteger)anTypeIndex
{
    switch (selectIndex) {
       
        case 5:{
            _selectedIndex3 = anIndex;
            
            _lbBoxType.text = [NSString stringWithFormat:@"%@",[[arrayBoxType objectAtIndex:anIndex] objectForKey:@"boxTypeDesc"]];
            boxType= [[[arrayBoxType objectAtIndex:anIndex] objectForKey:@"boxTypeID"] intValue];
            
            break;
        }
        case 6:{
            _selectedIndex2 = anIndex;
            
            _lbCapacity.text = [NSString stringWithFormat:@"%@",[[arrayCapacity objectAtIndex:anIndex] objectForKey:@"boxCaptcityDesc"]];
            capacityId= [[[arrayCapacity objectAtIndex:anIndex] objectForKey:@"boxCapacityID"] intValue];
           
            break;}
        default:
            break;
    }
    if (boxType==0 && capacityId==0) {
        tableDataArray = [allArray copy];
        [mainTable reloadData];
        _lbBoxType.text = @"包厢类型";
        _lbCapacity.text = @"包厢大小";

    }else if (boxType==0 ){
        _lbBoxType.text = @"包厢类型";
        tableDataArray = [[NSMutableArray alloc] init];
        for(int i=0;i<allArray.count;i++)
        {
            NSMutableDictionary *item = [allArray objectAtIndex:i];
//            NSLog(@"%@",item);
            if([[item objectForKey:@"SEAT_TYPE"]isEqualToString:_lbCapacity.text])
                [tableDataArray addObject:item];
        }
        [mainTable reloadData];
    }else if (capacityId==0 ){
        _lbCapacity.text = @"包厢大小";
        tableDataArray = [[NSMutableArray alloc] init];
        for(int i=0;i<allArray.count;i++)
        {
            NSMutableDictionary *item = [allArray objectAtIndex:i];
//            NSLog(@"%@",item);
            if([[item objectForKey:@"BOX_TYPE"]isEqualToString:_lbBoxType.text])
                [tableDataArray addObject:item];
        }
        [mainTable reloadData];

    }else{
        tableDataArray = [[NSMutableArray alloc] init];
        for(int i=0;i<allArray.count;i++)
        {
            NSMutableDictionary *item = [allArray objectAtIndex:i];
//            NSLog(@"%@",item);
           
            if([[item objectForKey:@"BOX_TYPE"]isEqualToString:_lbBoxType.text]
               &&[[item objectForKey:@"SEAT_TYPE"]isEqualToString:_lbCapacity.text])
                [tableDataArray addObject:item];
            
        }
        [mainTable reloadData];
    }
    if (tableDataArray.count==0) {
        [OMGToast showWithText:search_empty_msg bottomOffset:100];
    }
    
//    if (capacityId==0) {
//        tableDataArray = [allArray copy];
//        [mainTable reloadData];
//        _lbCapacity.text = @"包厢大小";
//    }else{
//        tableDataArray = [[NSMutableArray alloc] init];
//        for(int i=0;i<allArray.count;i++)
//        {
//            NSMutableDictionary *item = [allArray objectAtIndex:i];
//            NSLog(@"%@",item);
//            if([[item objectForKey:@"SEAT_TYPE"]isEqualToString:_lbCapacity.text])
//                [tableDataArray addObject:item];
//        }
//        [mainTable reloadData];
//    }

//    [self getSearchResult];
}
- (void)leveyPopListViewDidCancel
{
    //edtCity.text = @"You have cancelled";
}
@end
